package com.wangt.drools.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wangt.api.domain.DroolsRule;
import com.wangt.drools.config.DroolsManager;
import com.wangt.drools.mapper.DroolsRuleMapper;
import com.wangt.drools.service.IDroolsRuleService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.io.*;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;

@Service
@AllArgsConstructor
public class DroolsRuleServiceImpl  implements IDroolsRuleService {


    private final DroolsManager droolsManager;

    private final DroolsRuleMapper baseMapper;

    /**
     * 模拟数据库
     */
    private Map<Long, DroolsRule> droolsRuleMap = new HashMap<>(16);

    @Override
    public List<DroolsRule> findAll() {
        List<DroolsRule> droolsRules = baseMapper.selectList(new QueryWrapper<>());
        return droolsRules;
    }

    @Override
    public void addDroolsRule(DroolsRule droolsRule) {
       baseMapper.insert(droolsRule);
        droolsManager.addOrUpdateRule(droolsRule);
    }

    @Override
    public void updateDroolsRule(DroolsRule droolsRule) {
        baseMapper.updateById(droolsRule);
        droolsManager.addOrUpdateRule(droolsRule);
    }

    @Override
    public void deleteDroolsRule(Long ruleId, String ruleName) {
        DroolsRule droolsRule = baseMapper.selectById(ruleId);
        if (null != droolsRule) {
            baseMapper.deleteById(ruleId);
            droolsManager.deleteDroolsRule(droolsRule.getKieBaseName(), droolsRule.getKiePackageName(), ruleName);
        }
    }
    public static void main(String[] args) throws InterruptedException {
        try {
            // 和服务器创建连接
            Socket socket = new Socket("localhost",11000);
            // 要发送给服务器的信息
            OutputStream os = socket.getOutputStream();
            PrintWriter pw = new PrintWriter(os);
//            byte[] bytes = new byte[97 98 99 10 01 01 10 21 03 49];
//            pw.write(0xAA);
//
//
//
//            pw.flush();
            os.write("xxxxx".getBytes());


//            找到原因了，我代码里面写了个循环
            // 从服务器接收的信息
            InputStream is = socket.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            String info = null;
            while((info = br.readLine())!=null){
                System.out.println("我是客户端，服务器返回信息："+info);
            }
            socket.shutdownOutput();
            br.close();
            is.close();
            os.close();
            pw.close();
            socket.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
